package com.mokio.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.mokio.entity.*;
import com.mokio.service.*;
import com.mokio.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: xiaomishop
 * @ClassName ForeDetailController
 * @description:
 * @author: mokio
 * @create: 2024−12-20 18:35
 * @Version 1.0
 **/
@Controller
@RequestMapping("/fore")
public class ForeDetailController {
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private CarshopService carshopService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private XmorderService xmorderService;
    @Autowired
    private OrderService orderService;

    // /fore/detailOne.action?pid=${p.pId}
    @RequestMapping("/detailOne.action")
    public String detailOne(int pid,HttpSession session) {
        //根据id查询商品详情
        ProductInfo productById = productInfoService.findProductById(pid);
        session.setAttribute("prod", productById);
        return "redirect:/productdetail.jsp";
    }


    /**
     * 商品加入购物车 会根据原有商品判断新生成还是+1操作，同时判定只有登陆后才能操作
     * @param pid
     * @param model
     * @param session
     * @return
     */
    // /fore/carShop.action?pid=8
    @RequestMapping("/carShop.action")
    public String addCart(Integer pid, Model model, HttpSession session) {
      /*  private Integer cid;
        private Integer uid;
        private Integer pid;
        private Integer numbers;  */

        //获取User
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        Carshop carshop = new Carshop();
        carshop.setPid(pid);
        carshop.setUid(user.getUid());
        carshop.setNumbers(1);

        //掉用service方法
        boolean flag = carshopService.addCarShopOfCarshop(carshop);
        if (flag) {
            //添加购物车成功了
            //显示购物车
            return "redirect:/fore/showCarshop.action";
        }else {
            session.setAttribute("msg", "添加购物车失败");
            return "redirect:/productdetail.jsp";
        }

    }
    /**
     * 购物车信息展示
     *
     * @param session
     * @return
     */
    @RequestMapping("/showCarshop.action")
    public String showCarSop(HttpSession session) {
        //获取当前登录的用户信息
        Users user = (Users) session.getAttribute("user");

        List<Carshop> carshopList = carshopService.getAllCarShopByUserId(user.getUid());

        session.setAttribute("carlist", carshopList);

        return "redirect:/carshop.jsp";
    }

    //  fore/changeNumber.action
    @RequestMapping("changeNumber.action")
    public String changeNumber(int pid, Model model, HttpSession session) {
        return null;
    }

    // http://localhost:8080/xiaomishops_Web_exploded/fore/delete.action?cid=52
    //删除购物车
    @RequestMapping("/delete.action")
    public String deleteCarShopByCid(int cid) {
        carshopService.deleteByCid(cid);
        return "redirect:/fore/showCarshop.action";   //------------------------------------------
    }


    // http://localhost:8080/xiaomishop_Web_exploded/fore/showAddress.action
    @RequestMapping("/showAddress.action")
    public String showAddress( HttpSession session) {
        //获取当前登陆的用户的信息
        Users user = (Users) session.getAttribute("user");
        //一个人有多个地址  上学的 上班的 出差的 实际家里的
        List<Address> list=  addressService.findAddressByUid(user.getUid());
        session.setAttribute("addressList",list);
        return "redirect:/jiesuan.jsp";
    }



    @RequestMapping("/zhifu.action")
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    public void zhifu(HttpServletRequest request, HttpServletResponse response) {
        //地址可能新增不？
        //订单表添加数据不？
        //订单明细表添加多条数据
        //扣减库存
        //使用事务

        //获取用户信息
        Users user = (Users) request.getSession().getAttribute("user");
        //购物车从session中拿到
        List<Carshop> carshopList = (List<Carshop>) request.getSession().getAttribute("carlist");
        //创建地址对象
        Address address = new Address();
        //设置地址id
        Integer aid = -1;

        //获取用户选择的商品
        String[] pids = request.getParameterValues("pid");

        String showadd = request.getParameter("showadd");

        if (showadd != null) {
            Integer uid = user.getUid();
            //复选框被选中了 想要新增地址
            String cnee = request.getParameter("cnee");
            String phone = request.getParameter("phone");
            String newaddress = request.getParameter("newaddress");

            address.setUid(uid);
            address.setCnee(cnee);
            address.setAddress(newaddress);
            address.setPhone(phone);
            //新的地址存入数据库
            addressService.insertAddress(address);
            aid = addressService.findAddressIdByExample(address);
        } else {
            aid = Integer.parseInt(request.getParameter("rdo"));
        }


        //处理订单
        Xmorder xmorder = new Xmorder();
        //订单所有者
        xmorder.setUid(user.getUid());
        xmorder.setAddressid(aid);
        xmorder.setStatus("已支付");
        //总金额
        double total = Double.parseDouble(request.getParameter("total"));
        xmorder.setTotalprice(total);
        xmorder.setOdate(new Date());
        xmorder.setRemarks("赶快支付，否则取消订单");
        //订单编号
        String oid = UUID.randomUUID().toString().replace("-", "").substring(0, 11);
        //java.util.UUID
        xmorder.setOid(oid);

        //添加订单 ****************************************debug
        int num = xmorderService.save(xmorder, pids, carshopList);

        if (num > 0) {
            //添加订单成功了 ，成功了进行支付
            response.setContentType("text/html;charset=UTF-8");

            AlipayClient alipayClient =
                    new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                            AlipayConfig.app_id,
                            AlipayConfig.merchant_private_key,
                            "JSON", AlipayConfig.charset,
                            AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            // 服务器异步通知页面路径
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
            // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
            alipayRequest.setReturnUrl(AlipayConfig.return_url);

            //设置参数
            String subject = "小米商城的订单支付";
            String out_trade_no = oid;
            Double total_amount = total;


            alipayRequest.setBizContent("{" +
                    "    \"out_trade_no\":\"" + oid + "\"," +
                    "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                    "    \"total_amount\":" + total + "," +
                    "    \"subject\":\"" + subject + "\"," +
                    "    \"body\":\"" + subject + "\"," +
                    "    \"timeout_express\":\"90m\"" + "}");

            //请求
            String result = "";

            try {
                result = alipayClient.pageExecute(alipayRequest).getBody();

                response.setContentType("text/html;charset=" + AlipayConfig.charset);
                //将结果输出到 页面上
                response.getWriter().write(result);
                response.getWriter().flush();
                response.getWriter().close();

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    //  /fore/showOrder.action
//    @RequestMapping("/showOrder.action")
//    public String showOrder(HttpSession session, Model model) {
//        // 获取当前登录用户
//        Users user = (Users) session.getAttribute("user");
//        if (user == null) {
//            // 如果用户未登录，重定向到登录页面
//            return "redirect:/login.jsp";
//        }
//
//        // 查询当前用户的所有订单
//        List<Orderdetail> orderList = orderService.findOrdersByUserId(user.getUid());
//        //List<Xmorder> orderList = xmorderService.findOrdersByUserId(user.getUid());
//
//        // 将订单列表和用户信息存储到 Model 中
//        /*model.addAttribute("user", user);
//        model.addAttribute("orderList", orderList);*/
//
//        session.setAttribute("orderList", orderList);
//        session.setAttribute("user", user);
//
//        // 返回订单页面
//        return "redirect:/myorder.jsp";
//    }
    //  http://localhost:8080/xiaomishop_war_exploded/fore/logout.action
    @RequestMapping("/logout.action")
    public String logout(HttpSession session) {
        // 移除用户信息
        session.removeAttribute("user");
        // 重定向到登录页面
        return "redirect:/main.jsp";
    }

    //全部订单
    @RequestMapping("/showOrder.action")
    public String showOrder(HttpSession session) {
        Integer uid = ((Users) session.getAttribute("user")).getUid();
        List<Xmorder> o = xmorderService.findOrdersByUserId(uid);
        session.setAttribute("orderList",o);

        return "redirect:/myorder.jsp";
    }

}
